<?php declare(strict_types=1);

namespace App\Console\Commands\SyncOrderStatus;


use App\Api\Controllers\Merchant\OrderController;
use App\Models\Order;
use App\Services\PrintSqlService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Tymon\JWTAuth\Facades\JWTAuth;

class CronSyncOrderStatusCommand extends Command
{
    protected $signature = 'cron:sync-order-status';
    protected $description = 'cron:sync-order-status';

    public function __construct()
    {
        parent::__construct();
    }

    //同步订单状态
    public function handle()
    {
        //运行定时任务
        Log::channel("syncOrder")->info("start_CronSyncOrderStatusCommand_" . date("Y-m-d H:i:s", time()));
        $this->syncOrderStatus();
        Log::channel("syncOrder")->error("end_CronSyncOrderStatusCommand_" . date("Y-m-d H:i:s", time()));
    }

    public function syncOrderStatus()
    {
//        $nowTime = time();
//        $lastTime = $nowTime - (480 + 5);
//        $endTime = $nowTime - (60);
        $startDate = date("Y-m-d 00:00:00", time());
        $endDate = date("Y-m-d H:i:s", time() - 60);
        PrintSqlService::listen();
        Order::query()->whereBetween("created_at", [$startDate, $endDate])
            ->whereIn("dk_jf", [0, 1, 2, 3, 4])
            ->where("pay_status", 2)
            ->chunk(500, function ($orders) {
                foreach ($orders as $order) {
//                  $res = $this->http_curl('https://pay.zgjindoufu.com/api/basequery/update_order', json_encode($post_data));
                    Log::channel("syncOrder")->error("query" . date("Y-m-d H:i:s", time()), [
                        "out_trade_no" => $order->out_trade_no,
                    ]);
                    $this->updateOrder($order->store_id, $order->out_trade_no);
                    Order::where('out_trade_no', $order->out_trade_no)->update([
                        "dk_jf" => DB::raw("dk_jf+1")
                    ]);
                }
            });
    }

    public function updateOrder(string $store_id, string $out_trade_no): void
    {
        try {
            $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
            $b = str_ireplace($a, "", $out_trade_no);
            $day = substr($b, 0, 8);
            $table = 'orders_' . $day;

            if (Schema::hasTable($table)) {
                $order = Order::query()->from($table)->where('out_trade_no', $out_trade_no)
                    ->where('store_id', $store_id)
                    ->first();
            } else {
                $order = Order::where('out_trade_no', $out_trade_no)
                    ->where('store_id', $store_id)
                    ->first();
            }
            if (!$order) {
                return;
            }
            if ($order->pay_status == 6) {
                return;
            }
            $data = [
                'out_trade_no' => $order->out_trade_no,
                'store_id' => $order->store_id,
                'ways_type' => $order->ways_type,
                'config_id' => $order->config_id,
                'table' => $table,
            ];
            $obj = new OrderController();
            $return = $obj->order_foreach_public($data);
            if (!is_string($return) || empty($return = json_decode($return, true))) {
                Log::channel("syncOrder")->error("json_decodeStatus" . date("Y-m-d H:i:s", time()), [
                    "out_trade_no" => $order->out_trade_no,
                    "return" => $return
                ]);
                return;
            }
            //处理支付失败订单 1
            if ($return['pay_status'] == '3' || $return['pay_status'] == 3) {
                if (!empty($return['data']['out_trade_no'])) {
                    (new \App\Services\Pay\PayService())->closeOrder($return['data']['out_trade_no']);
                }
            }
            Log::channel("syncOrder")->error("successStatus" . date("Y-m-d H:i:s", time()), [
                "out_trade_no" => $order->out_trade_no,
                "return" => $return
            ]);
            //处理支付失败订单
        } catch (\Throwable $exception) {
            Log::channel("syncOrder")->error("exceptionStatus" . date("Y-m-d H:i:s", time()), [
                "out_trade_no" => $order->out_trade_no,
                "msg" => $exception->getMessage(),
                "line" => $exception->getLine(),
                "file" => $exception->getFile()
            ]);
        }
    }

}
